<?php

namespace App\Http\Controllers\V1\Upload;

use App\Models\V1\NewArrival;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use App\Events\V1\UploadFileEvent;
use Jenssegers\Agent\Agent;
use Log;

class BaseExcelUploadController extends Controller
{

    /**
     * 上传文件
     *
     * @param Request $request
     * @return array
     */
    protected function uploadExcel(Request $request)
    {
        // 获取request中操作者Code
        $code = $request->input('code');
        // 获取request中上传文件对象
        $file = $request->file('file');

        // 返回参数数组
        $response = [
            'rspStatus' => false,
            'rspMsg' => '文件[' . $file->getClientOriginalName() . '],上传失败！',
            'rspData' => [
                'originSrc' => '',
            ],
        ];

        if ($request->method() === 'POST') {
            // 验证request中上传的文件类型
            $isValid = $this->validFile($file);

            if ($isValid == false) {
                $response['rspMsg'] = '文件文件[' . $file->getClientOriginalName() . '],文件格式不正确！';
            }

            // 存储路径
            $storagePath = 'excel/';
            $storagePath .= $code;

            // 新文件名
            $newName = uniqid() . $file->getClientOriginalName();
//            Log::debug("storagePath is:" . $storagePath);
//            Log::debug("newName is:" . $newName);

            // 在指定目录保存Excel
            $originPath = Storage::disk('public')->putFileAs($storagePath, $file, $newName);

            // 检查文件是否上传成功
            $success = $this->checkFile($originPath);

            if ($success) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '文件[' . $file->getClientOriginalName() . $file->getClientOriginalExtension() . '],上传成功！';
                $response['rspData'] = [
                    'originSrc' => storage_path('app/public/') . $originPath,
                    'originExt' => $file->getClientOriginalExtension() ,
                ];

                // 上传成excel成功，触发事件
                event(new UploadFileEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspData']));
            }

            return $response;
        }
    }

    /**
     * 验证文件类型是否合法
     *
     * @param $objFile 文件对象
     * @return bool
     */
    protected function validFile($objFile)
    {
        // 合法文件类型
        $fileTypes = array('xls', 'xlsx', 'xlsm', 'csv');
        if (in_array($objFile->getClientOriginalExtension(), $fileTypes)) {
            return true;
        }
        return false;
    }

    /**
     * 验证文件是否上传成功
     *
     * @param $url
     * @return bool
     */
    protected function checkFile($url)
    {
        // 验证文件已存在
        $exists = Storage::disk('public')->exists($url);
        if ($exists) {
            return true;
        }
        return false;
    }

    protected function validateImport(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules = array_add($rules, 'captcha', 'bail|required|captcha');
        }
        $messages = $request->messages();

        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }


    protected function getArrivalCode()
    {
        $code = '';
        $years = NewArrival::where('isOn',true)->first();
        if (!empty($years) || isset($years)) {
            $code = $years->code;
        }
        return $code;
    }
}
